package com.zxl.permission.service;

import com.alibaba.fastjson.JSONObject;
import com.zxl.permission.dao.GroupDao;
import com.zxl.permission.entity.Detail;
import com.zxl.permission.entity.Group;
import com.zxl.permission.entity.UserGroup;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service("groupService")
public class GroupService {
    @Resource
    private GroupDao groupDao;

    public JSONObject list() {
        // 拉取用户组
        List<Group> groupList = groupDao.getGroupList();
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        res.put("data", groupList);
        return res;
    }

    public JSONObject detail(String groupname) {
        // 拉取权限详细信息
        List<Detail> permissionList = groupDao.getDetailListFromGroupname(groupname);
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        res.put("data", permissionList);
        return res;
    }

    public JSONObject add(Group group) {
        // 添加用户组
        Timestamp cur_time = new Timestamp(System.currentTimeMillis());
        group.create_time = cur_time;
        group.update_time = cur_time;
        groupDao.addGroup(group);
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        return res;
    }

    public JSONObject remove(String groupname) {
        // 删除用户组
        groupDao.removeGroupFromGroupname(groupname);
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        return res;
    }

    public JSONObject addUser(String groupname, String username) {
        // 查询用户组id
        List<Integer> group_id = groupDao.getGroupIdFromGroupName(groupname);
        // 添加用户所属用户组
        Timestamp cur_time = new Timestamp(System.currentTimeMillis());
        groupDao.addUserGroupByGroupId(group_id.get(0), username, cur_time);
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        return res;
    }

    public JSONObject userGroupList() {
        List<UserGroup> userGroupList = groupDao.getUserGroupList();

        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        res.put("data", userGroupList);
        return res;
    }
}
